﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using IndustrialSmokeCalc.SmokeCalcWCF;
using Telerik.Charting;
using Telerik.Windows.Controls;

namespace IndustrialSmokeCalc
{
    public partial class MeasurementDetailChart : PhoneApplicationPage
    {
        private double[] value;
        private int interval;
        private int[,] opacity;

        public MeasurementDetailChart()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            FillData();
            GetOpacityStatistic();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            double plotAreaWidth = chart.radChart.PlotAreaClip.Width;
            double zoomWidth = chart.radChart.Zoom.Width * plotAreaWidth;
            double maxOffsetX = plotAreaWidth - zoomWidth;
            chart.radChart.PanOffset = new Point(maxOffsetX, 0);
        }

        private void toggleBenchmark_Checked(object sender, RoutedEventArgs e)
        {
            toggleBenchmark.Content = "On";
            legendBenchmark.Visibility = Visibility.Visible;

            double topHighest = CalculateTopMargin(chart.radChart.ActualHeight, value[0]);
            chart.lineHighest.Margin = new Thickness(43,12+topHighest,35,0);
            chart.lineHighest.Visibility = Visibility.Visible;

            double topAverage = CalculateTopMargin(chart.radChart.ActualHeight, value[2]);
            chart.lineAverage.Margin = new Thickness(43, 12 + topAverage, 35, 0);
            chart.lineAverage.Visibility = Visibility.Visible;

            double topLowest = CalculateTopMargin(chart.radChart.ActualHeight, value[1]);
            chart.lineLowest.Margin = new Thickness(43, 12 + topLowest, 35, 0);
            chart.lineLowest.Visibility = Visibility.Visible;
        }

        private double CalculateTopMargin(double height, double val)
        {
            return (height - 45.0) / 100.0 * (100.0 - val);
        }

        private void toggleBenchmark_Unchecked(object sender, RoutedEventArgs e)
        {
            toggleBenchmark.Content = "Off";
            legendBenchmark.Visibility = Visibility.Collapsed;
            chart.lineHighest.Visibility = Visibility.Collapsed;
            chart.lineAverage.Visibility = Visibility.Collapsed;
            chart.lineLowest.Visibility = Visibility.Collapsed;
        }

        private void GetOpacityStatistic()
        {
            SmokeCalcClient client = new SmokeCalcClient();
            client.GetOpacityStatisticCompleted += GetOpacityStatisticCompleted;
            client.GetOpacityStatisticAsync();
        }

        private void GetOpacityStatisticCompleted(object sender, GetOpacityStatisticCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Tidak dapat melakukan koneksi ke server.\r\nCoba periksa koneksi internet anda.");
                NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
            }
            else if (e.Result != null)
            {
                value = new double[]{ e.Result[0], e.Result[1], e.Result[2] };
                toggleBenchmark.IsEnabled = true;
            }
        }

        private void FillData()
        {
            List<ChartBusinessObject> itemsSource = new List<ChartBusinessObject>();
            int count = 0;
            ExtractOpacityDetail(DataSingleton.Instance.StringOpacity);
            ChartBusinessObject model = new ChartBusinessObject();

            for (int i = 0; i < opacity.GetLength(0); i++)
            {
                for (int j = 0; j < opacity.GetLength(1); j++)
                {
                    model = new ChartBusinessObject();
                    model.Value = Convert.ToDouble(opacity[i,j] * 20);

                    DateTime time = DateTime.ParseExact(DataSingleton.Instance.StartTime, "HH:mm:ss", null);

                    model.Category = String.Format("{0}", time.AddSeconds(interval * ++count).ToString("HH:mm:ss"));
                    itemsSource.Add(model);
                }
            }

            chart.radChart.Zoom = new Size((count / 8) + 1, 1);
            chart.radChart.MaxZoom = new Size((count / 8) + 2, 1);
            chart.radChart.DataContext = itemsSource;
        }

        private void ExtractOpacityDetail(string input)
        {
            string[] minutes = input.Split('|');

            opacity = new int[minutes.Length, minutes[0].Length];

            int k = 0;
            for (int i = 0; i < minutes.Length; i++)
            {
                char[] seconds = minutes[i].ToCharArray();
                for (int j = 0; j < seconds.Length; j++)
                {
                    opacity[i, j] = seconds[0] - 48;
                }
            }

            interval = 60/minutes[0].Length;
        }

        private void ChartTrackBallBehavior_TrackInfoUpdated(object sender, TrackBallInfoEventArgs e)
        {
            CategoricalDataPoint dataPoint = e.Context.ClosestDataPoint.DataPoint as CategoricalDataPoint;
            e.Context.ClosestDataPoint.DisplayHeader = "Detail Pengamatan";
            e.Context.ClosestDataPoint.DisplayContent = "Pukul: " + dataPoint.Category + Environment.NewLine + "Nilai opasitas: " + dataPoint.Value;
        }

        private void ChartTooltipBehavior_ContextNeeded(object sender, TooltipContextNeededEventArgs e)
        {
            CategoricalDataPoint dataPoint = (CategoricalDataPoint)e.DefaultContext.ClosestDataPoint.DataPoint;
            e.Context = new ChartBusinessObject
            {
                Value = (double)dataPoint.Value,
                Category = dataPoint.Category.ToString(),
            };
        }
    }
}